package com.invengo.module_robot.ui.fragment.popular;

import android.annotation.SuppressLint;
import android.app.Application;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableList;

import com.invengo.base.http.RobotRxUtils;
import com.invengo.library_orionstar.ActionEvent;
import com.invengo.library_orionstar.RobotManager;
import com.invengo.library_orionstar.SpeechEvent;
import com.invengo.module_robot.BR;
import com.invengo.module_robot.R;
import com.invengo.module_robot.data.entity.PopularBean;
import com.invengo.module_robot.data.entity.TempBookBean;
import com.invengo.module_robot.data.repsitory.RobotRepsitory;
import com.invengo.module_robot.ui.fragment.popular.item.PopularItemViewModel;
import com.invengo.module_robot.ui.fragment.search.item.SearchItemViewModel;

import java.util.Optional;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.Messenger;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.utils.KLog;
import me.tatarka.bindingcollectionadapter2.ItemBinding;

public class PopularViewModel extends BaseViewModel<RobotRepsitory> {
    private int currentPosition = 0;
    private int moveSize = 6;
    private boolean isMove2Buttom = false;


    public SingleLiveEvent<String> tipContent = new SingleLiveEvent<>();
    public SingleLiveEvent<String> bookName = new SingleLiveEvent<>();
    public ObservableList<PopularItemViewModel> bookItemList = new ObservableArrayList<>();
    public ItemBinding<PopularItemViewModel> bookitemBinding = ItemBinding.of(BR.viewModel, R.layout.item_popular_book);

    UIChangeObservable ui = new UIChangeObservable();

    public class UIChangeObservable {
        public SingleLiveEvent<Integer> moveEvent = new SingleLiveEvent<>();
        public SingleLiveEvent<TempBookBean> itemEvent = new SingleLiveEvent<>();
        public SingleLiveEvent<Void> finishLoadEvent = new SingleLiveEvent<>();

    }

    public PopularViewModel(@NonNull Application application) {
        super(application, RobotRepsitory.getInstance());
    }


    /**
     * 受欢迎
     */
    public void getPopular() {
        bookItemList.clear();
        model.getPopularBook()
                .compose(RobotRxUtils.applySchedulers(getLifecycleProvider(), this,true))
                .subscribe(popularBeans -> {
                    for (PopularBean popularBean : popularBeans) {
                        TempBookBean bean = new TempBookBean();
                        bean.analyzePopularBook(popularBean);
                        bookItemList.add(new PopularItemViewModel(PopularViewModel.this,bean));
                    }
                });
    }


    public int getPosition(PopularItemViewModel viewModel) {
        return bookItemList.indexOf(viewModel);
    }

    /**
     * 启动信息
     *
     * @param bean 豆
     */
    public void launchInfo(TempBookBean bean) {
        ui.itemEvent.postValue(bean);
    }

    /**
     * 设置当前位置
     *
     * @param mFirstVisiblePosition m第一个可见位置
     */
    public void setCurrentPosition(int mFirstVisiblePosition) {
        this.currentPosition = mFirstVisiblePosition;
    }

    /**
     * 设置move2按钮
     *
     * @param canScrollVertically 可以垂直滚动
     */
    public void setMove2Buttom(boolean canScrollVertically) {
        isMove2Buttom = canScrollVertically;
    }


    public BindingCommand goBack = new BindingCommand(() -> {
        getUC().getOnBackPressedEvent().call();
    });


    public BindingCommand launchMain = new BindingCommand(() -> {
        getUC().getFinishActivityEvent().call();
    });

    public BindingCommand<String> searchCommand = new BindingCommand<>(question -> {
        Observable.just(question)
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(s -> {
                    searchList(question);
                });
    });

    @SuppressLint("NewApi")
    private void searchList(String keyWord) {
        Optional<PopularItemViewModel> first = bookItemList.stream().filter(b -> b.bookName.getValue().equals(keyWord))
                .findFirst();
        if (first.isPresent()) {
            Messenger.getDefault().send(SpeechEvent.answer("好的！"),"SPEECH_TO_PAGE");
            ui.itemEvent.postValue(first.get().getBookBean());
        } else {
            Messenger.getDefault().send(SpeechEvent.answer("列表中没有该图书，您可以说“图书查找”跳转查询！"),"SPEECH_TO_PAGE");
        }
    }

    private void move2Next() {    //移动到下一页
        ui.moveEvent.postValue(currentPosition + moveSize);
    }

    private void move2Pre() {    //移动到上一页
        ui.moveEvent.postValue(currentPosition - moveSize <= 0 ? 0 : (isMove2Buttom ? currentPosition : currentPosition - moveSize));
    }

    public BindingCommand<ActionEvent> actionCommand = new BindingCommand<>(action -> {
        Observable.just(action)
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(event -> {
                    switch (action.getEvent()) {

                        case ActionEvent.ACTION_DOWN:
                            move2Next();
                            break;
                        case ActionEvent.ACTION_UP:
                            move2Pre();
                            break;
                        case ActionEvent.ACTION_MOVE_TOP:
                            if (bookItemList.size() > 0)
                                ui.moveEvent.postValue(0);
                            break;
                        case ActionEvent.ACTION_MOVE_BUTTOM:
                            if (bookItemList.size() > 0)
                                ui.moveEvent.postValue(bookItemList.size() - 1);
                            break;
                    }
                });
    });

}
